<script setup>
  
  import { reactive } from 'vue'

  const carts = reactive([
    {name:'可乐',price:3,number:10},
    {name:'薯片',price:6,number:8}
    ])
    
    // 计算总金额
    function compute() {
      let count = 0;
      for (let index in carts) {
        count += carts[index].number*carts[index].price
      }
      return count
    }

    // 删除购物车的购物项的方法
    function removeCart(index) {
      carts.splice(index,1)
    }
    // 清空购物车
    function clearCart() {
      carts.splice(0,carts.length)
    }
</script>

<template>
  <div>
    <table border="1px">
      <thead>
        <tr>
          <th>序号</th>
          <th>商品名</th>
          <th>价格</th>
          <th>数量</th>
          <th>小计</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody v-if="carts.length > 0">
        <tr v-for = "cart,index in carts" v-bind:key="index">
          <td v-text="index+1"></td>
          <td v-text="cart.name"></td>
          <td v-text="cart.price"></td>
          <td v-text="cart.number"></td>
          <td v-text="cart.price*cart.number"></td>
          <td><button @click="removeCart(index)">删除</button></td>
        </tr>
      </tbody>
      <tbody v-else>
        <tr>
          <td colspan="6"> 购物车没有数据</td>
        </tr>
      </tbody>
    </table>
    <button @click="clearCart()">一键清空购物车</button><br>

    购物车总金额：{{compute()}}
  </div>
</template>

<style scoped>

</style>
